package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Override
    public PageResult getByPage(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<DishVO> page=dishMapper.getByPage(dto);



        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void add(DishDTO dishDTO) {
        Dish bean = BeanUtil.toBean(dishDTO, Dish.class);
        dishMapper.insert(bean);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(bean.getId());
        }

        dishFlavorMapper.insert(flavors);

    }

    @Override
    public void delete(List<Long> ids) {
        dishMapper.delete(ids);
        dishFlavorMapper.delete(ids);
    }

    @Override
    public DishVO getById(Long id) {
        Dish dish = dishMapper.selectById(id);
        DishVO bean = BeanUtil.toBean(dish, DishVO.class);
        List<DishFlavor> dishFlavors=dishFlavorMapper.selectByDishId(id);
        bean.setFlavors(dishFlavors);
        return bean;
    }

    @Override
    public void update(DishDTO dishDTO) {
        Dish bean = BeanUtil.toBean(dishDTO, Dish.class);
        dishMapper.update(bean);
        dishFlavorMapper.deleteByDishId(bean.getId());
        dishFlavorMapper.insert(dishDTO.getFlavors());
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        dishMapper.updateStatus(id,status);
    }
}
